var happyReaderImg = {
    setting:{
        bigImg: {
            width: 320,
            height: 320
        },
        smallImg: {
            width: 60,
            height: 60
        },
        picMode:{
            "width" : {
                scrollBarCtlWidth : [100,217,452,800],   //height = Math.ceil(width / 1.3)
                imgWidth : [86,265,546,1020],
                imgHeight : [60,184,420,700]
            },
            "height" : {
                scrollBarCtlWidth : [100,222,384,800],   //height = width * 1.3
                imgWidth : [80,200,354,770],
                imgHeight : [88,300,510,980]
            }
        }
    },
    imgData:{
        big:[],
        normal:[],
        small:[]
    },
    imgTitleData:{
        big:{}
    },
    imgAltData:{
        big:{}
    },
    picListData:{
        big:"bigPic",
        normal:"normalPic",
        small:"smallPic"
    },
    picMode:"width",
    picFactor:1.3,
    picCurData:{status:'',scrollBarLevel:2},
    inited:false,
    maskDiv:null,
	maskLastIdx:'',
	maskPicStatus:'big',
	maskShown:false,
	checkedImgList:{},
	checkedImgListLen:0,
	isDealSpecialSite:false,
	cloneImg:function(obj){
		return {src:obj.src, naturalWidth:obj.naturalWidth, naturalHeight:obj.naturalHeight, title:obj.title, alt:obj.alt, clickTitle:''};
	},
    specialSite:function(doc){
		if (this.isDealSpecialSite)return [];
		/* news */
		var doc = doc || document, host = doc.location.hostname, href = doc.location.href, imgs = [];
		if (/.*.163.com\/photoview\/(.*)/i.test(href)){
            var img, lis = doc.querySelectorAll('ul.nph_list_thumb > li');
			for(var i=0;i<lis.length; i++){
				img = new Image();
				img.src = lis[i].querySelector('i').innerHTML;
				img.title = img.alt = lis[i].querySelector('p').innerHTML;
				imgs.push(img);
			}
        }else if (/^slide.(.*).com.cn$/i.test(host)){
			var img, lis = doc.querySelectorAll('div#eData > dl');
			for(var i=0;i<lis.length; i++){
                img = new Image();
                img.src = lis[i].querySelector('dd').innerHTML;
                imgs.push(img);
            }
		}else if (/.*.ifeng.com\/photo\/(.*)/i.test(href) || /tech.ifeng.com\/digi\/dc\/smxj\/(.*)/i.test(href)) {
			var html, img, scripts = doc.querySelectorAll('[type="text/javascript"]:not(:empty)');
			for(var i=0; i<scripts.length; i++) {
				html = scripts[i].innerHTML;
				if (html.indexOf('var _listdata') < 0) {
					continue;
				}
				try {eval(html);}catch(e){}
                if (_listdata) {
                    _listdata.forEach(function(item, idx){
                        imgs.push(happyReaderImg.genImg(item.timg, item.title, item.picwidth, item.picheight));
                    });
                    _listdata = null;
                }
                break;
			}
		}else if (/www.chinanews.com\/tp\/hd2011\/(.*)/i.test(href)) {
			var html, img, scripts = doc.querySelectorAll('script:not([type]):not([language]):not(:empty)');
            for(var i=0; i<scripts.length; i++) {
                html = scripts[i].innerHTML;
                if (html.indexOf('var picsJson') < 0) {
                    continue;
                }
                try {eval(html);}catch(e){}
                if (picsJson) {
                    picsJson.pics.forEach(function(item, idx){
						console.log(item);
                        imgs.push(happyReaderImg.genImg(item.bigPicUrl.replace('200x145_',''), item.alt));
                    });
                    picsJson = null;
                }
                break;
            }
		}else if (/(.*).huanqiu.com/i.test(host)) {
			var html, img, scripts = doc.querySelectorAll('script[language="javascript"]:not([type]):not(:empty)');
            for(var i=0; i<scripts.length; i++) {
                html = scripts[i].innerHTML;
                if (html.indexOf('var slide_data') < 0) {
                    continue;
                }
                try {eval(html);}catch(e){}
                if (slide_data) {
                    slide_data.images.forEach(function(item, idx){
                        imgs.push(happyReaderImg.genImg(item.image_url, item.intro));
                    });
                    slide_data = null;
                }
                break;
            }
		}
		
        
		/* ent */
		/* car */
		this.isDealSpecialSite = true;
		return imgs;
	},
	genImg:function(src, title, width, height){
		var img = new Image();
		img.src = src;
		if (title) {
			img.title = img.alt = title;
		}
		if (width > 0) {
			img.width = width;
		}
		if (height > 0) {
			img.height = height;
		}
		return img;
	},
	getData:function(contentDiv){
		function sort(imgArr,img){
            var flag = false, imgW = img.naturalWidth;
            for(var j = imgArr.length-1; j>=0; j--){
                if (imgW >= imgArr[j].naturalWidth){
                    imgArr.splice(j+1,0,img);
                    flag = true;
                    break;
                }
            }
            !flag && imgArr.push(img);
        }
        
		var imgData = {big:[],normal:[],small:[]};
        var bigImgSetting = this.setting.bigImg, smallImgSetting = this.setting.smallImg;
        var imgs = contentDiv.getElementsByTagName("img");
        var wBigImg = [], hBigImg = [], unBigImg = [];
        var wNormalImg = [], hNormalImg = [], unNormalImg = [];
        var imgTitleDataIdx = [], imgAltDataIdx = [], imgDataIdx = {big:[],normal:[],small:[]};
		for(var i=0,imgCnt=imgs.length; i<imgCnt; i++){
            var img = this.cloneImg(imgs[i]), 
			    imgW = img.naturalWidth, 
				imgH = img.naturalHeight, 
				imgParent = img.parentNode;
            //set img link
            if (imgParent && imgParent.tagName == "A"){
				img.clickTitle = imgParent.title;
            }
            //group imgs by size
            if (imgW >= bigImgSetting.width && imgH >= bigImgSetting.height){
				if ($.inArray(img.src, imgDataIdx.big)) {
				    continue;
				}
                if (imgW > imgH)
                    sort(wBigImg,img);
                else if(imgW < imgH)
                    sort(hBigImg,img);
                else
                    unBigImg.push(img);
                
                imgDataIdx.big.push(img.src);

                if (!$.inArray(img.title, imgTitleDataIdx)){
                    this.imgTitleData.big[img.src] = img.title;
                    imgTitleDataIdx.push(img.title);
                }
                if (!$.inArray(img.alt, imgAltDataIdx)){
                    this.imgAltData.big[img.src] = img.alt;
                    imgAltDataIdx.push(img.alt);
                }
            }else if (imgW <= smallImgSetting.width && imgH <= smallImgSetting.height){
                if ($.inArray(img.src,imgDataIdx.small)){
                    continue;
                }
				imgData.small.push(img);
                imgDataIdx.small.push(img.src);
            }else{
                if ($.inArray(img.src,imgDataIdx.normal)){
                    continue;
                }
				if (imgW > imgH)
                    sort(wNormalImg,img,"width");
                else if (imgW < imgH)
                    sort(hNormalImg,img,"height");
                else
                    unNormalImg.push(img);
                        
                imgDataIdx.normal.push(img.src);
            }
        }
        
		$.mergeArray(wBigImg, this.specialSite());
        this.picMode = (wBigImg.length > hBigImg.length) ? "width" : "height";
        var tmpImg = (this.picMode == "width") ? $.mergeArray(wBigImg, hBigImg) : $.mergeArray(hBigImg, wBigImg) ;
		imgData.big = $.mergeArray(tmpImg, unBigImg);
        tmpImg = (this.picMode == "width") ? $.mergeArray(wNormalImg, hNormalImg) : $.mergeArray(hNormalImg, wNormalImg);
        imgData.normal = $.mergeArray(tmpImg, unNormalImg);
		
		var srcFilter = [];
		this.imgData.big.forEach(function(img, idx){
			if (srcFilter.indexOf(img.src)<0){
				srcFilter.push(img.src);
			}
		});
		imgData.big.forEach(function(img, idx){
			if (srcFilter.indexOf(img.src) < 0) {
				srcFilter.push(img.src);
				happyReaderImg.imgData.big.push(img);
			}
		});
		this.imgData.normal = imgData.normal;
		this.imgData.small = imgData.small;
		return this.imgData;
    },
    init:function(){
		$('#happyReaderHeaderAD').attr({onclick:function(){happyReaderImg.runSlides();return false;}}).html("<a href>"+_m("imgModeHeaderAD")+"</a>");
        happyReader.setUserConfig("viewMode","img");
		if (this.inited)return ;
        this.inited = true;
		
        var rangeClassName = (document.compatMode == 'BackCompat') ? 'BackCompat' : '' ,
            imgHtml =
            '<div class="operate">'
                +'<b>'+_m("size")+'</b><input type="range" min="100" max="800" value="400" id="happyReaderScrollBar" class="" title="384 X 296">'
            +'</div>'
            +'<h2 id="bigLine" class="at">'+_m("big")+'(<span id="bigPicCount">{bigPicCount}</span>) <input id="select_all_big" type="checkbox"/><label id="label_select_all_big" for="select_all_big">'+_m("selectAll")+'</label> <span id="saveall_big" class="disable">'+_m("saveAll")+'</span></h2><ul id="bigPic" class="picList"></ul>'
            +'<h2 id="normalLine">'+_m("normal")+'(<span id="normalPicCount">{normalPicCount}</span>) <input id="select_all_normal" type="checkbox"/><label id="label_select_all_normal" for="select_all_normal">'+_m("selectAll")+'</label> <span id="saveall_normal" class="disable">'+_m("saveAll")+'</span></h2><ul id="normalPic" class="picList"></ul>'
            +'<h2 id="smallLine">'+_m("small")+'(<span id="smallPicCount">{smallPicCount}</span>) <input id="select_all_small" type="checkbox"/><label id="label_select_all_small" for="select_all_small">'+_m("selectAll")+'</label> <span id="saveall_small" class="disable">'+_m("saveAll")+'</span></h2><ul id="smallPic" class="picList"></ul>';
        
        imgHtml = imgHtml.replace('{bigPicCount}',this.imgData.big.length).replace('{normalPicCount}',this.imgData.normal.length).replace('{smallPicCount}',this.imgData.small.length);
        $('#imgCanvas').css({left:0}).html(imgHtml);
        
		$('#select_all_big').attr({
			onclick:function(e){e.stopPropagation();},
			onchange:function(e){
				e.stopPropagation();
                $('#label_select_all_big').html(this.checked ? _m('unSelectAll') : _m('selectAll'));
				this.checked ? happyReaderImg.selectAll('big') : happyReaderImg.unSelectAll('big');
			}
		});
        $('#label_select_all_big').attr({onclick:function(e){e.stopPropagation();}});
		
		$('#select_all_normal').attr({
            onclick:function(e){e.stopPropagation();},
            onchange:function(e){
                e.stopPropagation();
                $('#label_select_all_normal').html(this.checked ? _m('unSelectAll') : _m('selectAll'));
                this.checked ? happyReaderImg.selectAll('normal') : happyReaderImg.unSelectAll('normal');
            }
        });
        $('#label_select_all_normal').attr({onclick:function(e){e.stopPropagation();}});
		
		$('#select_all_small').attr({
            onclick:function(e){e.stopPropagation();},
            onchange:function(e){
                e.stopPropagation();
                $('#label_select_all_small').html(this.checked ? _m('unSelectAll') : _m('selectAll'));
                this.checked ? happyReaderImg.selectAll('small') : happyReaderImg.unSelectAll('small');
            }
        });
        $('#label_select_all_small').attr({onclick:function(e){e.stopPropagation();}});
		
        this.setView();
        this.addListener();
    },
    render:function(){
        var factor = this.picCurData.scrollBarLevel - 1;
        var status = this.picCurData.status;
        var imgs = this.imgData[status], ul = document.getElementById(this.picListData[status]);
        var baseFactor = this.setting.picMode[this.picMode].scrollBarCtlWidth[factor];
        var defaultImgWidth = this.setting.picMode[this.picMode].imgWidth[factor], defaultImgHeight = this.setting.picMode[this.picMode].imgHeight[factor];
        ul.innerHTML = "";
        for(var i=0;i<imgs.length;i++){
            var img = imgs[i],
			    checkID = status+'_check_'+i,
				textHeight = (factor > 0) ? 24 : 0 ;  //default picMode is width 
            if (this.picMode == "height")
                textHeight = (factor > 0) ? 70 : 0 ; 
            var li = document.createElement("li");
			li.id = 'li_'+status+'_img_'+ i;
            li.className = !!happyReaderImg.checkedImgList[checkID] ? 'cur' : '';
			li.style.width = ((this.picMode == "width") ? Math.ceil(baseFactor*this.picFactor) : baseFactor) + "px";
            li.style.height = ((this.picMode == "height") ? Math.ceil(baseFactor*this.picFactor) : baseFactor) +textHeight + "px"; 

            var imgHTML = "<img id='"+status+"_img_"+i+"' src="+img.src;
            if (img.naturalWidth > defaultImgWidth || img.naturalHeight > defaultImgHeight){
                if (img.naturalWidth > img.naturalHeight)
                    imgHTML += " width="+defaultImgWidth; 
                else
                    imgHTML += " height="+defaultImgHeight; 
            }
            imgHTML += " status='"+status+"' alt="+img.clickTitle+" />";
            
            var letterCount = -5*(factor+1), checkboxID = status+'_check_'+i;
            var imgTitle = (status == "big") ? this.imgTitleData.big[img.src] : img.title;
            var imgAlt = (status == "big") ? this.imgAltData.big[img.src] : img.alt;
            var imgName = (imgAlt ? imgAlt.slice(letterCount) : null) || (imgTitle ? imgTitle.slice(letterCount) : null) || img.src.slice(letterCount);
            li.innerHTML = '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">'
            +'<tr><td align="center" valign="middle">'+imgHTML+'<p class="photoBlank'+factor+'"><input id="'+checkboxID+'" type="checkbox" value="'+img.src+'"/><label for="'+checkboxID+'">'+imgName+'<br/>'+img.naturalWidth+'X'+img.naturalHeight+'</label></p><div class="tip"><tip><a id="'+status+'_save_'+i+'" href>'+_m('imgSaveCheckedImage')+'</a></tip></div></td></tr>'
            +'</table>';
            ul.appendChild(li);
            
            $('#'+status+'_save_'+i).attr({onclick: function(){happyReaderImg.saveCheckedImg();return false;}});
			$('#'+status+'_img_'+i).attr({onclick:function(){happyReaderImg.showMaskImg(this);}}).css({cursor:'pointer'});
			$('#'+checkID).attr({checked:!!happyReaderImg.checkedImgList[checkID], onclick:function(){happyReaderImg.checkboxHandle(this);}});
		}
    },
    setView:function(){
        var bigImgs = this.imgData.big, normalImgs = this.imgData.normal, smallImgs = this.imgData.small, 
            bigLine = $('#bigLine'), normalLine = $('#normalLine'), smallLine = $('#smallLine'), 
            bigPic = $('#bigPic'), normalPic = $('#normalPic'), smallPic = $('#smallPic'),
            _this = this;
        
        if (bigImgs.length > 0){
            this.picCurData.status = "big";
            bigPic.show();
            normalPic.hide();
            smallPic.hide();
            bigLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            normalLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }else if (normalImgs.length > 0){
            this.picCurData.status = "normal";
            bigPic.hide();
            normalPic.show();
            smallPic.hide();
            bigLine.attr({"className":""}).css({"cursor":"default"});
            normalLine.attr({"className":"at"});
            normalLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }else if (smallImgs.length > 0){
            this.picCurData.status = "small";
            bigPic.hide();
            normalPic.hide();
            smallPic.show();
            bigLine.attr({"className":""}).css({"cursor":"default"});
            normalLine.attr({"className":""}).css({"cursor":"default"});
            smallLine.attr({"className":"at"});
            smallLine[0].onclick = function(){
                _this.viewSwitch(this);
            }
        }
        this.render();
    },
    viewSwitch:function(obj){
        var status = this.picCurData.status = obj.id.split("Line")[0];
        obj.nextSibling.style.display = (obj.className == "at") ? "none" : "block";
        obj.className = (obj.className == "at") ? "" : "at";
        this.render();
    },
    addListener:function(){
        var _this = this,
            scrollBar = $("#happyReaderScrollBar")[0];
        
        scrollBar.onchange = function(e){
            var newLevel = Math.ceil(this.value / 200);
            if (newLevel == _this.picCurData.scrollBarLevel) {
                return;
            }
            
            _this.picCurData.scrollBarLevel = newLevel;
            var oldStatus = _this.picCurData.status;
            for(var key in _this.imgData){
                _this.picCurData.status = key;
                _this.render();
            }
            _this.picCurData.status = oldStatus;
        }
        scrollBar.onmouseover = scrollBar.onmousemove = function(e){
            var position = Math.ceil((e.clientX-parseInt(_m("scrollBarOffset")))/30);
            var w = _this.setting.picMode[_this.picMode].scrollBarCtlWidth[position-1];
            this.title = w + " X " + ((_this.picMode == "width") ? Math.ceil(w*_this.picFactor): Math.ceil(w/_this.picFactor)) ;
        }
    },
    save:function(url){
        happyReader._downloadUrl(url);
    },
	/*
    saveAll:function(status){
        var imgs = document.getElementById(status+'Pic').getElementsByTagName('img');
        if (imgs.length){
            for(var i=0,img;img=imgs[i++];){
                happyReader._downloadUrl(img.src);
            }
        }
    },
    */
	saveCheckedImg:function(){
       for (var idx in this.checkedImgList){
	       happyReader._downloadUrl(this.checkedImgList[idx]);
	   }
    },
	runSlides:function(){
		this.showMaskImg($('#big_img_0')[0] || $('#normal_img_0')[0] || $('#small_img_0')[0]);
	},
    showMaskImg:function(self){
		if (!self)return;
		var maskAvailSize = this.getMaskAvailSize(),
            maskAWidth = maskAvailSize.width, 
            maskAHeight = maskAvailSize.height,
			imgWidth = self.naturalWidth || self.width,
			imgHeight = self.naturalHeight || self.height,
            imgMode = maskAWidth / imgWidth * imgHeight > maskAHeight ? 'height' : 'width',
            imgWidth2height = imgWidth/imgHeight,
			imgAttrWidth = Math.min(imgWidth, maskAWidth),
            imgAttrHeight = Math.min(imgHeight, maskAHeight),
            imgAttr = imgMode == 'width' ? 
                     {width:imgAttrWidth, height:1/imgWidth2height*imgAttrWidth} : 
                     {width:imgWidth2height*imgAttrHeight, height:imgAttrHeight};
	    
		this.maskPicStatus = self.getAttribute('status');
		this.maskShown = true;
		if (!this.maskDiv){
            var html = "<div id='maskCanvas'><b id='closeMask'>X</b><img id='maskCanvasImg' /></div>"
            +"<div id='maskBar'>"
			  +"<span id='maskCurImgIdx'></span>"
              +"<span id='maskBarLarger'></span>"
              +"<span id='maskBarSmaller'></span>"
              +"<span id='maskBarSave'></span>"
              +"<span id='maskBarBack'></span>"
            +"</div>";
			
            this.maskDiv = $.createEle('div', {id:'happyReaderImgMask',onclick:function(){happyReaderImg.hideMaskImg()}}, {position:'absolute', top:0, left:0, width:'100%', height:'100%', background:'rgba(0,0,0,.7)'}).html(html).appendTo($('body'));
            $('#maskBar').attr({onclick:function(e){e.stopPropagation();return false;}});
			$('#maskBarSave').attr({onclick: function(){happyReaderImg.save(self.src);}});
            $('#maskBarBack').attr({onclick: function(){happyReaderImg.hideMaskImg();}});
        }
		happyReader.hideHeader();
        
        var curIdx = self.id.split('_').pop(),
		    marginTopValue = imgAttr.height ? (maskAHeight - imgAttr.height)/2+'px' : 0,
			maskImg = $('#maskCanvasImg').attr({onmousemove:function(e){happyReaderImg.setMaskImgCursor(e, this)}}).css({opacity:0});
			
		this.setMaskCurImgIdx(curIdx);
		this.setHighLight(curIdx);
		
		setTimeout(function(){
			maskImg.attr({src:self.src}).css({opacity:1, marginTop:marginTopValue}).attr(imgAttr)[0].setAttribute('idx', curIdx);
			happyReaderImg.showCloseBtn(imgAttr, maskAvailSize);
			setTimeout(function(){happyReaderImg.initMaskBarZoom();},500);
		},300);
		
        this.maskDiv.css({top:document.body.scrollTop+'px'}).show();
        $('body').css({'overflow-y':'hidden'});
		
		window.onmousewheel = function(e){
            if (e.wheelDelta > 0){
                happyReaderImg.preMaskImg();
            }else{
                happyReaderImg.nextMaskImg();
            }
        }
    },
    hideMaskImg:function(){
        window.onmousewheel = null;
		$('#maskCanvasImg').attr({width:0,height:0}).css({marginTop:0});
		this.maskShown = false;
		this.hideCloseBtn();
		happyReader.showHeader();
		setTimeout(function(){
			happyReaderImg.maskDiv.hide();
			happyReaderImg.clearHighLight();
            $('body').css({'overflow-y':'auto'});
		},700);
    },
    preMaskImg:function(){
		var curIdx = $('#maskCanvasImg')[0].getAttribute('idx');
		if (curIdx <= 0)return;
        this.clearHighLight();
		this.showMaskImg($('#'+this.maskPicStatus+'_img_'+(--curIdx))[0]);
    },
    nextMaskImg:function(){
		var curIdx = $('#maskCanvasImg')[0].getAttribute('idx');
		if (curIdx >= this.imgData[this.maskPicStatus].length - 1)return;
        this.clearHighLight();
		this.showMaskImg($('#'+this.maskPicStatus+'_img_'+(++curIdx))[0]);
    },
	setHighLight: function(idx){
		this.maskLastIdx = idx;
		$('#li_'+this.maskPicStatus+'_img_'+idx).attr({className:'cur'});
	},
	clearHighLight: function(idx){
		idx = idx || this.maskLastIdx;
		$('#li_'+this.maskPicStatus+'_img_'+idx).attr({className:''});
	},
	setMaskCurImgIdx: function(idx){
		idx = parseInt(idx) + 1 + '/' + this.imgData[this.maskPicStatus].length;
		$('#maskCurImgIdx').html(idx);
	},
	setMaskImgCursor:function(e, self){
		var _this = this,
		    curIdx = self.getAttribute('idx'),
		    isLeft = window.screen.availWidth/2 > e.clientX;

		self.className = isLeft ? 
		                 (curIdx <=0 ? '' : 'pre') : 
						 (curIdx >= _this.imgData[_this.maskPicStatus].length - 1 ? '' : 'next');

		self.onclick = function(e){
			e.stopPropagation();
            isLeft ? happyReaderImg.preMaskImg() : happyReaderImg.nextMaskImg();
			return false;		
		}
	},
	getMaskAvailSize:function(){
		var scr = window.screen;
	    return {width: scr.availWidth - 40, height: scr.availHeight - 105};//25 + 80
	},
	setMaskImgLarger:function(){
		this.resizeMaskImg(1);
	},
	setMaskImgSmaller:function(){
		this.resizeMaskImg(-1);
	},
	initMaskBarZoom:function(){
		this.resizeMaskImg(0);
	},
	resizeMaskImg:function(zoom){
		var seed = 1.15, 
		    newFactor = Math.pow(seed, zoom), 
			maskImg = $('#maskCanvasImg'), 
			newWidth = maskImg.attr('width') * newFactor, 
			newHeight = maskImg.attr('height') * newFactor,
			imgSize = {width: newWidth, height: newHeight},
			nextFactor = zoom ? newFactor : seed,
			nextWidth = newWidth * nextFactor, 
			nextHeight = newHeight * nextFactor, 
			maskAvailSize = this.getMaskAvailSize(), 
			maskAWidth = maskAvailSize.width, 
			maskAHeight = maskAvailSize.height, 
			marginTopValue = (maskAHeight - newHeight) / 2 + 'px';
		
		if (zoom != 0) {	
			this.setCloseBtnPos(imgSize, maskAvailSize);
			maskImg.attr(imgSize).css({marginTop: marginTopValue});
		}
		
        var cssEnable = {cursor:'pointer', color:''}, 
            cssDisable = {cursor:'', color:'#ccc'},
            largerCss = cssEnable,
            smallerCss = cssEnable, 
            largerAttr = {onclick: function(){happyReaderImg.setMaskImgLarger();}},
            smallerAttr = {onclick: function(){happyReaderImg.setMaskImgSmaller();}},
            attrDisable = {onclick:null};
        
		if (nextWidth > maskAWidth || nextHeight > maskAHeight) {
			largerAttr = attrDisable;
			largerCss = cssDisable;
		}else if (nextWidth < 100 || nextHeight < 100) {
			smallerAttr = attrDisable;
			smallerCss = cssDisable;
		}

        $('#maskBarSmaller').attr(smallerAttr).css(smallerCss);
        $('#maskBarLarger').attr(largerAttr).css(largerCss);
	},
	setCloseBtnPos:function(imgSize, maskAvailSize){
		var topValue = (maskAvailSize.height - imgSize.height)/2 + 'px',
		    rightValue = (maskAvailSize.width - imgSize.width)/2 + 'px';
		$('#closeMask').css({top:topValue, right:rightValue});
	},
	showCloseBtn:function(imgSize, maskAvailSize){
		this.setCloseBtnPos(imgSize, maskAvailSize);
		setTimeout(function(){
			$('#closeMask').show();
		},550);
	},
	hideCloseBtn:function(){
		$('#closeMask').hide();
	},
	checkModeValid:function(){
		return this.imgData.big.length > 2;
	},
	checkboxHandle:function(self){
		var checked = self.checked, 
		    info = self.id.split('_'),
			status = info.shift(),
			idx = info.pop(),
			imgLi = $('#li_'+status+'_img_'+idx);

		if (checked){
			imgLi.attr({className:'cur'});
			this.checkedImgList[self.id] = self.value;
			if (++this.checkedImgListLen == 1) {
				this.bindSaveSelectedImgBtn();
			}
			if (this.checkedImgListLen == this.imgData[status].length) {
				$('#select_all_'+status).attr({checked:true});
                $('#label_select_all_'+status).html(_m('unSelectAll'));
			}
			var tipStyle = imgLi[0].getElementsByTagName('tip')[0].style;
			tipStyle.top = '-42px';
			tipStyle.opacity = 1;
			setTimeout(function(){
				tipStyle.top = 0;
				tipStyle.opacity = 0;
			},2000);
		}else{
			imgLi.attr({className:''});
			delete this.checkedImgList[self.id];
			if (--this.checkedImgListLen == 0) {
	            this.unBindSaveSelectedImgBtn();
	        }
			$('#select_all_'+status).attr({checked:false});
			$('#label_select_all_'+status).html(_m('selectAll'));
		}
	},
	selectAll:function(status){
		var imgs = this.getImgsByStatus(status);
		imgs.forEach(function(img, i){
            $('#li_'+status+'_img_'+i).attr({className:'cur'});
            $('#'+status+'_check_'+i).attr({checked:true});
            happyReaderImg.checkedImgList[status+'_check_'+i] = img.src;
        });
		this.checkedImgListLen = imgs.length;
		this.bindSaveSelectedImgBtn();
    },
    unSelectAll:function(status){
		this.getImgsByStatus(status).forEach(function(img, i){
			$('#li_'+status+'_img_'+i).attr({className:''});
            $('#'+status+'_check_'+i).attr({checked:false});
            delete happyReaderImg.checkedImgList[status+'_check_'+i];
		});
		this.checkedImgListLen = 0;
		this.unBindSaveSelectedImgBtn();
    },
	getImgsByStatus:function(status){
		var imgs = document.getElementById(status+'Pic').getElementsByTagName('img'),
            len = imgs.length,
            res = [];
        
        if (len==0)return res;
		for(var i=0,img; img=imgs[i++];) {
			res.push(img);
		}
		return res;
	},
	bindSaveSelectedImgBtn:function(){
		$('#saveall_big').attr({className:'', onclick:function(e){e.stopPropagation();happyReaderImg.saveCheckedImg();return false;}});
		$('#saveall_normal').attr({className:'', onclick:function(e){e.stopPropagation();happyReaderImg.saveCheckedImg();return false;}});
		$('#saveall_small').attr({className:'', onclick:function(e){e.stopPropagation();happyReaderImg.saveCheckedImg();return false;}});
	},
	unBindSaveSelectedImgBtn:function(){
        $('#saveall_big').attr({className:'disable', onclick:null});
        $('#saveall_normal').attr({className:'disable', onclick:null});
        $('#saveall_small').attr({className:'disable', onclick:null});
    }
};